package com.yksj.healthtalk.ui.doctorstation;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.DoctorServiceContentListAdapter;
import com.yksj.healthtalk.adapter.DoctorServiceContentListAdapter.OnClickDeleteListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.entity.DoctorServiceContentEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 服务内容列表
 * @author Administrator
 *
 */
public class DoctorServiceContentList extends BaseFragmentActivity implements OnClickListener,OnClickDeleteListener{
	private ListView mListView;
	private PullToRefreshListView refreshListView;
	private List<DoctorServiceContentEntity> entities=new ArrayList<DoctorServiceContentEntity>();
	private DoctorServiceContentListAdapter adapter;
	private String SERVICE_ITEM_ID="";
	private String SERVICE_TYPE_ID;
	private String SERVICE_TYPE_SUB_ID;
	private String mParameList;
	private boolean Activity_RESULT_OK=false;
	private List<String> createIsCHECK;//创建前选择的

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_service_content_list);
		initTitle();
		SERVICE_TYPE_ID=getIntent().getStringExtra("SERVICE_TYPE_ID");
		if(getIntent().hasExtra("SERVICE_ITEM_ID"))
		SERVICE_ITEM_ID = getIntent().getStringExtra("SERVICE_ITEM_ID");
		
		SERVICE_TYPE_SUB_ID = getIntent().getStringExtra("SERVICE_TYPE_SUB_ID");
		initView();
	}

	private void initView() {
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("服务内容");
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setText("创建");
		titleRightBtn2.setVisibility(View.VISIBLE);
		
		findViewById(R.id.deleted_all).setOnClickListener(this);
		
		refreshListView = (PullToRefreshListView)findViewById(R.id.listview_fragment);
		mListView = refreshListView.getRefreshableView();
		adapter = new DoctorServiceContentListAdapter(entities,this,this,0);
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		mListView.setAdapter(adapter);
		initData();
	}
	
	private void initData() {
		HttpRestClient.doHttpQueryDoctorContent(SERVICE_TYPE_SUB_ID,SERVICE_TYPE_ID,SERVICE_ITEM_ID,new ObjectHttpResponseHandler(this) {
			@Override
			public Object onParseResponse(String content) {
				return DoctorServiceContentEntity.parsoToList(content);
			}
			@Override
			public void onSuccess(Object response) {
				super.onSuccess(response);
				if(response!=null){
					adapter.onBoundData((List<DoctorServiceContentEntity>)response);
					getIntentData();
				}else{
					onFailure(null);
				}
			}
		});
	}
	
	private void getIntentData(){
		if(getIntent().hasExtra("isChoise")){
			List<String> isChoise=getIntent().getStringArrayListExtra("isChoise");
			for (int i = 0; i < isChoise.size(); i++) {
				String ischosed=isChoise.get(i);
				int size = adapter.entities.size();
				for (int j = 0; j < size; j++) {
					if(adapter.entities.get(j).getSERVICE_CONTENT_ID().equals(ischosed)){
						adapter.entities.get(j).setISSELECT("1");
					}
				}
			}
			adapter.notifyDataSetChanged();
		}
		if(Activity_RESULT_OK&&createIsCHECK!=null){
				for (int i = 0; i < createIsCHECK.size(); i++) {
					String ischosed=createIsCHECK.get(i);
					int size = adapter.entities.size();
					for (int j = 0; j < size; j++) {
						if(adapter.entities.get(j).getSERVICE_CONTENT_ID().equals(ischosed)){
							adapter.entities.get(j).setISSELECT("1");
							break;
						}
					}
				}
				adapter.notifyDataSetChanged();
				createIsCHECK=null;
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode!=Activity.RESULT_OK)return;
		switch (requestCode) {
		case 2000:
			if(data.hasExtra("array")){
				Activity_RESULT_OK=true;
				createIsCHECK=data.getStringArrayListExtra("array");
			}
			initData();
			break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(KeyEvent.KEYCODE_BACK==keyCode){
			DoctorServiceContentEntity entity;
			int size=adapter.entities.size();
			JSONArray array=new JSONArray();
			for (int i = 0; i <size; i++) {
				entity=adapter.entities.get(i);
				if("1".equals(entity.getISSELECT())){
					array.put(entity.getSERVICE_CONTENT_ID());
				}
			}
			if(array.length()<=0){
				mParameList="[]";
			}else{
				mParameList=array.toString();
			}
			
			if(SERVICE_ITEM_ID==null||"".equals(SERVICE_ITEM_ID)){
				Intent intent = getIntent();
				intent.putExtra("parame", mParameList);
				setResult(RESULT_OK, intent);
				finish();
			}else{
				submint(mParameList);
			}
			return true;
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_back:
			DoctorServiceContentEntity entity;
			int size=adapter.entities.size();
			JSONArray array=new JSONArray();
			for (int i = 0; i <size; i++) {
				entity=adapter.entities.get(i);
				if("1".equals(entity.getISSELECT())){
					array.put(entity.getSERVICE_CONTENT_ID());
				}
			}
			if(array.length()<=0){
				mParameList="[]";
			}else{
				mParameList=array.toString();
			}
			
			if(SERVICE_ITEM_ID==null||"".equals(SERVICE_ITEM_ID)){
				intent = getIntent();
				intent.putExtra("parame", mParameList);
				setResult(RESULT_OK, intent);
				finish();
				overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
			}else{
				submint(mParameList);
			}
			break;
			
		case R.id.title_right2:
			int arraysize=adapter.entities.size();
			List<String> list=new ArrayList<String>();
			for (int i = 0; i <arraysize; i++) {
				entity=adapter.entities.get(i);
				if("1".equals(entity.getISSELECT())){
					list.add(entity.getSERVICE_CONTENT_ID());
				}
			}
			intent=new Intent(this,DoctorServiceAddContent.class);
			Bundle bundle=new Bundle();
			bundle.putParcelableArrayList("entitys", (ArrayList<? extends Parcelable>) adapter.entities);
			bundle.putStringArrayList("array", (ArrayList<String>) list);
			intent.putExtras(bundle);
			startActivityForResult(intent,2000);
			break;
			
		case R.id.deleted_all://已删除的服务内容
			intent=new Intent(this,DoctorServiceContentDeletedListActivity.class);
			intent.putExtra("SERVICE_ITEM_ID", SERVICE_ITEM_ID);
			startActivityForResult(intent,2000);
			break;
		}
	}
	//选择服务内容提交
	private void submint(final String parame) {
		HttpRestClient.doHttpDoctorSubmintServiceContent(SERVICE_ITEM_ID,parame,new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				try {
					JSONObject object=new JSONObject(content);
					if(object.has("error_message")){
						ToastUtil.showBasicShortToast(getApplicationContext(), object.optString("error_message")+"");
					}else{
						Intent intent = getIntent();
						intent.putExtra("parame", mParameList);
						setResult(RESULT_OK,getIntent());
						finish();
						overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
					}
				} catch (JSONException e) {
				}
			}
		});
	}

/*	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		DoctorServiceContentEntity entity =adapter.entities.get(position-1);
		if("System".equals(entity.getSERVICE_TYPE()))return;
		Intent intent=new Intent(this,DoctorServiceAddContent.class);
		Bundle bundle=new Bundle();
		bundle.putSerializable("entity", entity);
		bundle.putParcelableArrayList("entitys", (ArrayList<? extends Parcelable>) adapter.entities);
		intent.putExtras(bundle);
		startActivityForResult(intent,2000);
	}*/
	
	//删除
	@Override
	public void onclick(final DoctorServiceContentEntity entity) {
		DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "确认要删除服务内容《"+entity.getSERVICE_CONTENT()+"》吗？", "取消", "确定", new OnDilaogClickListener() {
			@Override
			public void onDismiss(DialogFragment fragment) {
				fragment.dismissAllowingStateLoss();
			}
			
			@Override
			public void onClick(DialogFragment fragment, View v) {
				HttpRestClient.doHttpDeleteServiceItem(entity.getSERVICE_CONTENT_ID(),new AsyncHttpResponseHandler(DoctorServiceContentList.this){
					@Override
					public void onSuccess(int statusCode, String content) {
						super.onSuccess(statusCode, content);
						try {
							JSONObject object=new JSONObject(content);
							if(object.has("error_message")){
								ToastUtil.showBasicShortToast(getApplicationContext(), object.optString("error_message")+"");
							}else{
								ToastUtil.showBasicShortToast(getApplicationContext(), "删除成功");
								initData();
							}
						} catch (JSONException e) {
						}
					}
				});
			}
		});
	}
}
